﻿using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using MySqlConnector;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XKJ.OAWeb.Infrastructrue
{
    public class Dapper
    {
        //读取配置文件
        private IConfiguration Configuration { get; set; }
        //返回连接实例
        private static IDbConnection dbConnection = null;
        //静态变量保存类的实例
        private static Dapper uniqueInstance;
        //定义一个标识确保线程同步
        private static readonly object locker = new object();
        /// <summary>
        /// 私有构造方法，使外界不能创建该类的实例，以便实现单例模式
        /// </summary>
        private Dapper()
        {
            Configuration = new ConfigurationBuilder()
            .Add(new JsonConfigurationSource
            {
                Path = "appsettings.json",
                ReloadOnChange = true
            }).Build();
        }
        /// <summary>
        /// 获取实例，这里为单例模式，保证只存在一个实例
        /// </summary>
        /// <returns></returns>
        public static Dapper GetInstance()
        {
            //双重锁定实现单例模式，外层判空条件是为了减少加锁、释放的不必要消耗
            if (uniqueInstance==null)
            {
                lock (locker)
                {
                    if (uniqueInstance==null)
                    {
                        uniqueInstance = new Dapper();
                    }
                }
            }
            return uniqueInstance;
        }
        /// <summary>
        /// 创建数据库连接对象（采用了设计模式 之 工厂模式）
        /// </summary>
        /// <returns></returns>
        public IDbConnection GetDbConnection()
        {
            //如果数据库连接为空，则重新连接
            if (dbConnection==null)
            {
                //读取配置文件中的数据库服务器类型 mysql或sqlserve
                string dbType = Configuration["DbServerType"];
                //读取配置文件中的连接字符串
                string _connectionStrings = Configuration.GetConnectionString("conn");
                switch (dbType)
                {
                    case "MySQL":
                        dbConnection = new MySqlConnection(_connectionStrings);
                        break;
                    case "SQLServer":
                        dbConnection = new SqlConnection(_connectionStrings);
                        break;
                }
            }
            return dbConnection;
        }
    }
}
